package demo.controller;

import com.alibaba.fastjson.JSONObject;
import com.jfinal.core.Controller;
import com.jfinal.core.Path;
import com.jfinal.kit.Kv;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Page;
import demo.model.User;

import java.util.Date;

@Path("/user")
public class UserController extends Controller {
    public void index() {
        render("user.html");
    }

    public void list() {
        int page = getParaToInt("page");
        int limit = getParaToInt("limit");
        String userName = getPara("userName");
        //String realName = getPara("realName");
        //Page<User> userPage = User.dao.paginate(page,limit,"select * ", "from sys_user");
        Page<User> userPage = User.dao.template("getList", new Kv().by("userName",userName)).paginate(page,limit);
        System.out.println("用户名参数：" + userName);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code",0);
        jsonObject.put("msg","操作成功");
        jsonObject.put("count", userPage.getTotalRow());
        jsonObject.put("data", userPage.getList());
        renderJson(jsonObject);
    }

    public void add() {
        System.out.println("更新");
        User user = new User();
        String username = getPara("userName");
        String realname = getPara("realName");
        String gender = getPara("gender");

        user.setUserName(username);
        user.setRealName(realname);
        user.setGender(gender);
        user.setPassWord("123");
        user.setCreatTime(new Date());
        user.save();

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code",200);
        jsonObject.put("msg","保存成功");
        renderJson(jsonObject);
    }

    public void update() {
        String id = getPara("id");
        String username = getPara("userName");
        String realname = getPara("realName");
        String gender = getPara("gender");
        User user = User.dao.findById(id);
        user.setUserName(username);
        user.setRealName(realname);
        user.setGender(gender);
        user.update();

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code",200);
        jsonObject.put("msg","更新成功");
        renderJson(jsonObject);

    }

    public void delete() {
        String id = getPara("id");
        String ids = getPara("ids");
        if(StrKit.notBlank(id)) {
            User.dao.deleteById(id);
        } else {
            String [] idArra = ids.split(",");
            for (String myId: idArra) {
                User.dao.deleteById(myId);
            }
        }

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code",200);
        jsonObject.put("msg","删除成功");
        renderJson(jsonObject);
    }

}
